<!--
  Copyright [2025] [OBARA (Nanjing) Electromechanical Co., Ltd]

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->


{% extends 'base.html' %}

{% load tz %}

{% block title %}用户管理 - 小原焊枪选型数据库{% endblock %}

{% block content %}
<div class="row">
    <div class="col-12">
        <div class="d-flex justify-content-between align-items-center mb-4 fade-in-up">
            <h1 class="display-6 fw-bold">
                <i class="bi bi-people me-2"></i>
                用户管理
            </h1>
            <div>
                {% if user.is_superuser %}
                    <button type="button" class="btn btn-info me-2" onclick="exportUsers()">
                        <i class="bi bi-download me-2"></i>
                        导出用户信息
                    </button>
                {% endif %}
                <button type="button" class="btn btn-success me-2" data-bs-toggle="modal" data-bs-target="#addUserModal">
                    <i class="bi bi-person-plus me-2"></i>
                    新增用户
                </button>
                <a href="{% url 'clamps:management_dashboard' %}" class="btn btn-outline-secondary">
                    <i class="bi bi-arrow-left me-2"></i>
                    返回仪表板
                </a>
            </div>
        </div>
        
        <!-- 用户列表 -->
        <div class="card fade-in-up">
            <div class="card-header">
                <h5 class="mb-0">
                    <i class="bi bi-list me-2"></i>
                    用户列表
                </h5>
            </div>
            <div class="card-body">
                {% if users_with_profiles %}
                    <div class="table-responsive">
                        <table class="table table-hover">
                            <thead>
                                <tr>
                                    <th>用户名</th>
                                    <th>用户备注</th>
                                    <th>密码备注</th>
                                    <th>状态</th>
                                    <th>权限</th>
                                    <th>密码状态</th>
                                    <th>下载限制</th>
                                    <th>注册时间</th>
                                    <th>最后登录</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                {% for item in users_with_profiles %}
                                    {% with user=item.user profile=item.profile password_expired=item.password_expired %}
                                    <tr>
                                        <td>
                                            <strong>{{ user.username }}</strong>
                                        </td>
                                        <td>
                                            {% if profile.customer_name %}
                                                {{ profile.customer_name }}
                                            {% else %}
                                                --
                                            {% endif %}
                                        </td>
                                        <td>
                                            {% if user.first_name or user.last_name %}
                                                {{ user.first_name }} {{ user.last_name }}
                                            {% else %}
                                                --
                                            {% endif %}
                                        </td>
                                        <td>
                                            {% if user.is_active %}
                                                <span class="badge bg-success">
                                                    <i class="bi bi-check-circle me-1"></i>
                                                    活跃
                                                </span>
                                            {% else %}
                                                <span class="badge bg-danger">
                                                    <i class="bi bi-x-circle me-1"></i>
                                                    停用
                                                </span>
                                            {% endif %}
                                        </td>
                                        <td>
                                            {% if user.is_superuser %}
                                                <span class="badge bg-danger">
                                                    <i class="bi bi-shield-fill me-1"></i>
                                                    超级管理员
                                                </span>
                                            {% elif user.is_staff %}
                                                <span class="badge bg-warning">
                                                    <i class="bi bi-person-badge me-1"></i>
                                                    管理员
                                                </span>
                                            {% else %}
                                                <span class="badge bg-primary">
                                                    <i class="bi bi-person me-1"></i>
                                                    普通用户
                                                </span>
                                            {% endif %}
                                        </td>
                                        <td>
                                            {% if profile.password_validity_days == 0 %}
                                                <span class="badge bg-info">
                                                    <i class="bi bi-infinity me-1"></i>
                                                    永久有效
                                                </span>
                                            {% elif password_expired %}
                                                <span class="badge bg-danger">
                                                    <i class="bi bi-exclamation-triangle me-1"></i>
                                                    已过期
                                                </span>
                                            {% else %}
                                                <span class="badge bg-success">
                                                    <i class="bi bi-clock me-1"></i>
                                                    {{ profile.password_validity_days }}天有效
                                                </span>
                                            {% endif %}
                                        </td>
                                        <td>
                                            <small class="text-muted">
                                                单次: {{ profile.max_single_download_mb }}MB<br>
                                                批量: {{ profile.max_batch_download_mb }}MB<br>
                                                每日: {{ profile.max_daily_download_gb }}GB / {{ profile.max_daily_download_count }}个
                                            </small>
                                        </td>
                                        <td>
                                            <small class="text-muted">
                                                {{ user.date_joined|date:"Y-m-d H:i" }}<br>
												创建者: {{ item.created_by }}
                                            </small>
                                        </td>
                                        <td>
                                            <small class="text-muted">
												{% if user.last_login %}
													{{ user.last_login|timezone:"Asia/Shanghai"|date:"Y-m-d H:i" }}
												{% else %}
													从未登录
												{% endif %}
                                            </small>
                                            <br>
											<small class="text-muted">
												截止: 
												{% if item.password_expiry_date == "永久有效" %}
													{{ item.password_expiry_date }}
												{% else %}
													{{ item.password_expiry_date|timezone:"Asia/Shanghai"|date:"Y-m-d H:i" }}
												{% endif %}
											</small>
                                        </td>
										<!-- 操作列 -->
										<td>
											{% if not user.is_superuser and user != request.user %}
											<div class="d-flex align-items-center" style="gap: 0.5rem;">
												<!-- 停用/激活按钮 -->
												<form method="post" class="mb-0">
													{% csrf_token %}
													{% if user.is_active %}
														<input type="hidden" name="action" value="deactivate">
														<input type="hidden" name="user_id" value="{{ user.id }}">
														<button type="submit" class="btn btn-outline-danger btn-sm d-inline-flex align-items-center"
																data-bs-toggle="tooltip" title="停用用户"
																onclick="return confirm('确定要停用用户 {{ user.username }} 吗？')">
															<i class="bi bi-x-circle"></i>
														</button>
													{% else %}
														<input type="hidden" name="action" value="activate">
														<input type="hidden" name="user_id" value="{{ user.id }}">
														<button type="submit" class="btn btn-outline-success btn-sm d-inline-flex align-items-center"
																data-bs-toggle="tooltip" title="激活用户"
																onclick="return confirm('确定要激活用户 {{ user.username }} 吗？')">
															<i class="bi bi-check-circle"></i>
														</button>
													{% endif %}
												</form>

												<!-- 配置按钮 -->
												<button type="button" class="btn btn-outline-primary btn-sm d-inline-flex align-items-center"
														data-bs-toggle="modal" data-bs-target="#configModal{{ user.id }}"
														data-bs-toggle="tooltip" title="配置用户">
													<i class="bi bi-gear"></i>
												</button>

												<!-- 重置密码按钮 -->
												<button type="button" class="btn btn-outline-warning btn-sm d-inline-flex align-items-center"
														data-bs-toggle="modal" data-bs-target="#setPasswordModal{{ user.id }}"
														data-bs-toggle="tooltip" title="重置密码">
													<i class="bi bi-key"></i>
												</button>
											</div>
											{% elif user.is_superuser %}
												<span class="text-muted small">超级管理员</span>
											{% elif user == request.user %}
												<span class="text-muted small">当前用户</span>
											{% endif %}
										</td>
                                    </tr>
                                    {% endwith %}
                                {% endfor %}
                            </tbody>
                        </table>
                    </div>
                {% else %}
                    <div class="text-center py-5">
                        <i class="bi bi-people text-muted" style="font-size: 4rem;"></i>
                        <h3 class="mt-3 text-muted">暂无用户</h3>
                        <p class="text-muted">系统中还没有注册用户</p>
                    </div>
                {% endif %}
            </div>
        </div>
        
        <!-- 用户统计 -->
        <div class="row mt-4">
            <div class="col-md-3">
                <div class="card text-center fade-in-up">
                    <div class="card-body">
                        <i class="bi bi-people text-primary" style="font-size: 2rem;"></i>
                        <h4 class="mt-2">{{ users_with_profiles|length }}</h4>
                        <p class="text-muted mb-0">总用户数</p>
                    </div>
                </div>
            </div>
            
            <div class="col-md-3">
                <div class="card text-center fade-in-up">
                    <div class="card-body">
                        <i class="bi bi-check-circle text-success" style="font-size: 2rem;"></i>
                        <h4 class="mt-2">{{ active_users_count }}</h4>
                        <p class="text-muted mb-0">活跃用户</p>
                    </div>
                </div>
            </div>
            
            <div class="col-md-3">
                <div class="card text-center fade-in-up">
                    <div class="card-body">
                        <i class="bi bi-person-badge text-warning" style="font-size: 2rem;"></i>
                        <h4 class="mt-2">{{ admin_users_count }}</h4>
                        <p class="text-muted mb-0">管理员</p>
                    </div>
                </div>
            </div>
            
            <div class="col-md-3">
                <div class="card text-center fade-in-up">
                    <div class="card-body">
                        <i class="bi bi-exclamation-triangle text-danger" style="font-size: 2rem;"></i>
                        <h4 class="mt-2">{{ password_expired_count }}</h4>
                        <p class="text-muted mb-0">密码过期</p>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 操作说明 -->
        <div class="card mt-4 fade-in-up">
            <div class="card-header">
                <h5 class="mb-0">
                    <i class="bi bi-info-circle me-2"></i>
                    操作说明
                </h5>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-3">
                        <h6>用户状态管理</h6>
                        <ul class="list-unstyled">
                            <li class="mb-2">
                                <i class="bi bi-check-circle text-success me-2"></i>
                                <strong>激活：</strong>允许用户登录和使用系统
                            </li>
                            <li class="mb-2">
                                <i class="bi bi-x-circle text-danger me-2"></i>
                                <strong>停用：</strong>禁止用户登录和使用系统
                            </li>
                        </ul>
                    </div>
                    <div class="col-md-3">
                        <h6>密码有效期</h6>
                        <ul class="list-unstyled">
                            <li class="mb-2">
                                <i class="bi bi-infinity text-info me-2"></i>
                                <strong>永久：</strong>密码永不过期
                            </li>
                            <li class="mb-2">
                                <i class="bi bi-clock text-success me-2"></i>
                                <strong>限期：</strong>1-15天后过期，可任意设置
                            </li>
                            <li class="mb-2">
                                <i class="bi bi-exclamation-triangle text-danger me-2"></i>
                                <strong>过期：</strong>需要配置密码有效期进行续期
                            </li>
                        </ul>
                    </div>
                    <div class="col-md-3">
                        <h6>下载限制</h6>
                        <ul class="list-unstyled">
                            <li class="mb-2">
                                <i class="bi bi-file-earmark text-primary me-2"></i>
                                <strong>单次限制：</strong>单个文件最大下载大小
                            </li>
                            <li class="mb-2">
                                <i class="bi bi-files text-info me-2"></i>
                                <strong>批量限制：</strong>批量下载最大总大小
                            </li>
                            <li class="mb-2">
                                <i class="bi bi-calendar-day text-warning me-2"></i>
                                <strong>每日限制：</strong>每天总下载量和文件数
                            </li>
                        </ul>
                    </div>
                    <div class="col-md-3">
                        <h6>配置建议</h6>
                        <ul class="list-unstyled">
                            <li class="mb-2">
                                <i class="bi bi-lightbulb text-warning me-2"></i>
                                <strong>批量下载：</strong>设置为单次限制的5-10倍
                            </li>
                            <li class="mb-2">
                                <i class="bi bi-shield-check text-success me-2"></i>
                                <strong>安全考虑：</strong>根据用户权限合理设置
                            </li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 新增用户模态框 -->
<div class="modal fade" id="addUserModal" tabindex="-1" aria-labelledby="addUserModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="addUserModalLabel">
                    <i class="bi bi-person-plus me-2"></i>
                    新增用户
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form method="post" action="{% url 'clamps:add_user' %}" onsubmit="return validatePasswords()">
                {% csrf_token %}
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="username" class="form-label">用户名 <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="username" name="username" required>
                        <div class="form-text">用户名为英文小写4~10字符长度，最好与客户拼音名相关，不能重复</div>
                    </div>
                    <div class="mb-3">
                        <label for="customer_name" class="form-label">客户名称 <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="customer_name" name="customer_name" required>
                        <div class="form-text">备注客户名称，方便查找和统计相关客户使用系统的信息情况</div>
                    </div>
                    <div class="mb-3">
                        <label for="password" class="form-label">密码 <span class="text-danger">*</span></label>
                        <input type="password" class="form-control" id="password" name="password" required oninput="checkPasswordMatch()">
                        <div class="form-text">设置安全的密码，最好为在用户名后面加上ochn</div>
                    </div>
					<div class="mb-3">
                        <label for="password_remark" class="form-label">密码备注 <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="password_remark" name="password_remark" required oninput="checkPasswordMatch()">
                        <div id="passwordMatchFeedback" class="form-text">再次输入密码，必须和上面的密码一致</div>
                    </div>
                    <div class="alert alert-info">
                        <i class="bi bi-info-circle me-2"></i>
                        <strong>默认设置：</strong>
                        <ul class="mb-0 mt-2">
                            <li>用户类型：普通用户</li>
                            <li>密码有效期：5天</li>
                            <li>单次下载限制：100MB</li>
                            <li>批量下载限制：200MB</li>
                            <li>每日下载限制：10GB / 100个文件</li>
                        </ul>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="submit" class="btn btn-success">
                        <i class="bi bi-check me-1"></i>
                        创建用户
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- 用户配置模态框 -->
{% for item in users_with_profiles %}
    {% with user=item.user profile=item.profile %}
    <div class="modal fade" id="configModal{{ user.id }}" tabindex="-1" aria-labelledby="configModalLabel{{ user.id }}" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="configModalLabel{{ user.id }}">
                        <i class="bi bi-gear me-2"></i>
                        配置用户：{{ user.username }}
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form method="post">
                    {% csrf_token %}
                    <input type="hidden" name="action" value="update_config">
                    <input type="hidden" name="user_id" value="{{ user.id }}">
                    <div class="modal-body">
                        <div class="row">
                            <div class="col-md-6">
                                <h6 class="mb-3">
                                    <i class="bi bi-key me-2"></i>
                                    密码有效期设置
                                </h6>
                                <div class="mb-3">
                                    <label for="passwordValidity{{ user.id }}" class="form-label">密码有效期</label>
                                    <select class="form-select" id="passwordValidity{{ user.id }}" name="password_validity_days">
                                        {% for value, label in password_validity_choices %}
                                            <option value="{{ value }}" {% if profile.password_validity_days == value %}selected{% endif %}>
                                                {{ label }}
                                            </option>
                                        {% endfor %}
                                    </select>
                                    <div class="form-text">
										<!-- 修改密码有效期后，截止时间将从今天开始重新计算。 -->
                                        密码最后修改时间：{{ profile.password_last_changed|date:"Y-m-d H:i" }}
                                        <br>
                                        <small class="text-info">
                                            <i class="bi bi-info-circle me-1"></i>
                                            可设置1-15天或永久有效，默认5天
                                        </small>
                                    </div>
                                </div>
                                
                                <h6 class="mb-3 mt-4">
                                    <i class="bi bi-person-lines-fill me-2"></i>
                                    用户信息编辑
                                </h6>
                                <div class="mb-3">
                                    <label for="customerName{{ user.id }}" class="form-label">用户备注</label>
                                    <input type="text" class="form-control" id="customerName{{ user.id }}" 
                                           name="customer_name" value="{{ profile.customer_name|default:'' }}" 
                                           placeholder="请输入客户名称或备注信息">
                                    <div class="form-text">用于备注客户名称或其他相关信息</div>
                                </div>
                                <div class="mb-3">
                                    <label for="passwordRemark{{ user.id }}" class="form-label">密码备注</label>
                                    <input type="text" class="form-control" id="passwordRemark{{ user.id }}" 
                                           name="password_remark" value="{{ user.first_name|default:'' }} {{ user.last_name|default:'' }}" 
                                           placeholder="请输入密码相关备注">
                                    <div class="form-text">如不记得用户密码禁止输入，此操作不会变更用户密码</div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <h6 class="mb-3">
                                    <i class="bi bi-download me-2"></i>
                                    文件下载限制(大小为压缩前文件原始大小)
                                </h6>
                                <div class="mb-3">
                                    <label for="maxSingleDownload{{ user.id }}" class="form-label">单次最大下载大小（MB）</label>
                                    <input type="number" class="form-control" id="maxSingleDownload{{ user.id }}" 
                                           name="max_single_download_mb" value="{{ profile.max_single_download_mb }}" min="1" max="1000">
                                </div>
                                <div class="mb-3">
                                    <label for="maxBatchDownload{{ user.id }}" class="form-label">单次批量下载最大大小（MB）</label>
                                    <input type="number" class="form-control" id="maxBatchDownload{{ user.id }}" 
                                           name="max_batch_download_mb" value="{{ profile.max_batch_download_mb }}" min="1" max="5000">
                                    <div class="form-text">
                                        建议设置为单次下载限制的3-5倍，默认200MB
                                    </div>
                                </div>
                                <div class="mb-3">
                                    <label for="maxDailyDownloadGB{{ user.id }}" class="form-label">每日最大下载大小（GB）</label>
                                    <input type="number" class="form-control" id="maxDailyDownloadGB{{ user.id }}" 
                                           name="max_daily_download_gb" value="{{ profile.max_daily_download_gb }}" min="1" max="100">
                                </div>
                                <div class="mb-3">
                                    <label for="maxDailyDownloadCount{{ user.id }}" class="form-label">每日最大下载文件数</label>
                                    <input type="number" class="form-control" id="maxDailyDownloadCount{{ user.id }}" 
                                           name="max_daily_download_count" value="{{ profile.max_daily_download_count }}" min="1" max="1000">
                                </div>
                            </div>
                        </div>
                        <div class="row mt-3">
                            <div class="col-12">
                                <h6 class="mb-3">
                                    <i class="bi bi-bar-chart me-2"></i>
                                    今日下载统计(今日无下载则显示上次下载数据)
                                </h6>
                                <div class="row">
                                    <div class="col-md-4">
                                        <div class="card stats-card">
                                            <div class="card-body text-center">
                                                <h6 class="card-title">已下载大小</h6>
                                                <p class="card-text">{{ profile.daily_download_size_mb }} MB</p>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-4">
                                        <div class="card stats-card">
                                            <div class="card-body text-center">
                                                <h6 class="card-title">已下载文件数</h6>
                                                <p class="card-text">{{ profile.daily_download_count }} 个</p>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-4">
                                        <div class="card stats-card">
                                            <div class="card-body text-center">
                                                <h6 class="card-title">最后下载日期</h6>
                                                <p class="card-text">
                                                    {% if profile.last_download_date %}
                                                        {{ profile.last_download_date|date:"Y-m-d" }}
                                                    {% else %}
                                                        从未下载
                                                    {% endif %}
                                                </p>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                        <button type="submit" class="btn btn-primary">
                            <i class="bi bi-check me-1"></i>
                            保存配置
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    {% endwith %}
{% endfor %}

<!-- 重置密码模态框 -->
{% for item in users_with_profiles %}
    {% with user=item.user profile=item.profile %}
    <div class="modal fade" id="setPasswordModal{{ user.id }}" tabindex="-1" aria-labelledby="setPasswordModalLabel{{ user.id }}" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="setPasswordModalLabel{{ user.id }}">
                        <i class="bi bi-key me-2"></i>
                        重置密码：{{ user.username }}
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form method="post" onsubmit="return validateSetPassword({{ user.id }})">
                    {% csrf_token %}
                    <input type="hidden" name="action" value="set_password">
                    <input type="hidden" name="user_id" value="{{ user.id }}">
                    <div class="modal-body">
                        <div class="mb-3">
                            <label for="newPassword{{ user.id }}" class="form-label">新密码 <span class="text-danger">*</span></label>
                            <input type="password" class="form-control" id="newPassword{{ user.id }}" name="new_password" required 
                                   oninput="checkSetPasswordMatch({{ user.id }})">
                            <div class="form-text">设置安全的密码，最好为在用户名后面加上ochn</div>
                        </div>
                        <div class="mb-3">
                            <label for="passwordRemarkSet{{ user.id }}" class="form-label">密码备注 <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="passwordRemarkSet{{ user.id }}" name="password_remark" required 
                                   oninput="checkSetPasswordMatch({{ user.id }})">
                            <div id="passwordSetMatchFeedback{{ user.id }}" class="form-text">再次输入密码，必须和上面的密码一致</div>
                        </div>
                        <div class="alert alert-warning">
                            <i class="bi bi-exclamation-triangle me-2"></i>
                            <strong>注意：</strong>设置新密码后，用户需要使用新密码登录，密码备注将自动变更与新密码保持一致。
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                        <button type="submit" class="btn btn-warning">
                            <i class="bi bi-check me-1"></i>
                            设置密码
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    {% endwith %}
{% endfor %}
{% endblock %}

{% block extra_js %}
<script>
    // 初始化 Bootstrap Tooltips
    var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'))
    var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
      return new bootstrap.Tooltip(tooltipTriggerEl)
    })

    // 确认操作提示
    document.querySelectorAll('form button[type="submit"]').forEach(button => {
        button.addEventListener('click', function(e) {
            const form = this.closest('form');
            const action = form.querySelector('input[name="action"]');
            
            if (action && action.value !== 'update_config') {
                const username = this.closest('tr').querySelector('strong').textContent;
                
                let message = '';
                if (action.value === 'activate') {
                    message = `确定要激活用户 ${username} 吗？`;
                } else if (action.value === 'deactivate') {
                    message = `确定要停用用户 ${username} 吗？`;
                }
                
                if (message && !confirm(message)) {
                    e.preventDefault();
                }
            }
        });
    });

    // 导出用户信息功能
    function exportUsers() {
        if (confirm('确定要导出所有用户信息吗？')) {
            window.location.href = "{% url 'clamps:export_users' %}";
        }
    }
	
	// 检查密码是否匹配
	function checkPasswordMatch() {
		const password = document.getElementById('password').value;
		const passwordRemark = document.getElementById('password_remark').value;
		const feedbackElement = document.getElementById('passwordMatchFeedback');
		
		if (passwordRemark === '') {
			// 密码备注为空时显示默认提示
			feedbackElement.textContent = '再次输入密码，必须和上面的密码一致';
			feedbackElement.className = 'form-text';
			return false;
		} else if (password === passwordRemark) {
			// 密码匹配时显示成功提示
			feedbackElement.textContent = '密码一致';
			feedbackElement.className = 'form-text text-success';
			return true;
		} else {
			// 密码不匹配时显示错误提示
			feedbackElement.textContent = '密码不一致，请重新输入';
			feedbackElement.className = 'form-text text-danger';
			return false;
		}
	}

	// 表单提交前验证
	function validatePasswords() {
		if (!checkPasswordMatch()) {
			// 显示错误提示
			alert('密码不一致，请检查并重新输入');
			// 聚焦到密码备注字段
			document.getElementById('password_remark').focus();
			return false;
		}
		return true;
	}

	// 检查设置密码是否匹配（与新增用户逻辑一致）
	function checkSetPasswordMatch(userId) {
		const password = document.getElementById('newPassword' + userId).value;
		const passwordRemark = document.getElementById('passwordRemarkSet' + userId).value;
		const feedbackElement = document.getElementById('passwordSetMatchFeedback' + userId);
		
		if (passwordRemark === '') {
			// 密码备注为空时显示默认提示
			feedbackElement.textContent = '再次输入密码，必须和上面的密码一致';
			feedbackElement.className = 'form-text';
			return false;
		} else if (password === passwordRemark) {
			// 密码匹配时显示成功提示
			feedbackElement.textContent = '密码一致';
			feedbackElement.className = 'form-text text-success';
			return true;
		} else {
			// 密码不匹配时显示错误提示
			feedbackElement.textContent = '密码不一致，请重新输入';
			feedbackElement.className = 'form-text text-danger';
			return false;
		}
	}

	// 设置密码表单提交前验证
	function validateSetPassword(userId) {
		if (!checkSetPasswordMatch(userId)) {
			// 显示错误提示
			alert('密码不一致，请检查并重新输入');
			// 聚焦到密码备注字段
			document.getElementById('passwordRemarkSet' + userId).focus();
			return false;
		}
		
		// 确认设置密码
		const username = document.querySelector('#setPasswordModal' + userId + ' .modal-title').textContent.split('：')[1].trim(); // 使用 trim() 去除前后空白字符
		if (!confirm('确定要为用户 ' + username + ' 设置新密码吗？')) {
			return false;
		}
		
		return true;
	}
</script>
{% endblock %}